#include "myclient.h"
#include <QTcpSocket>
#include <QDebug>
#include <QJsonObject>
#include <QJsonDocument>

MyClient::MyClient(QObject *parent) : QObject(parent)
{
    socket = new QTcpSocket;

    connect(socket, &QTcpSocket::readyRead,
            this, &MyClient::socketReadyReadSlot);
    connect(socket, &QTcpSocket::connected,
            this, &MyClient::connected);
    connect(socket, &QTcpSocket::disconnected,
            this, &MyClient::disconnected);
}

MyClient::~MyClient()
{
    disconnected();
}

void MyClient::connectServer(QString ip, quint16 port)
{
    if(socket->state() == QTcpSocket::ConnectedState)
        disconnected();
    socket->connectToHost(ip, port);
}

void MyClient::disconnectServer()
{
    if(socket->state() != QTcpSocket::ConnectedState)
        return;
    socket->flush();
    socket->disconnectFromHost();
}

bool MyClient::getState()
{
    return socket->state() == QTcpSocket::ConnectedState ? true : false;
}

void MyClient::sendData(const QByteArray &data)
{
    if(socket->state() != QTcpSocket::ConnectedState)
        return;
    socket->write(data);
}

void MyClient::socketReadyReadSlot()
{
    QByteArray data;
    while(socket->bytesAvailable())
    {
        data.append(socket->readAll());
    }
//    emit receiveData(data);
    this->data.append(QString::fromLocal8Bit(data));
    handleData();
}

void MyClient::handleData()
{
    //循环判断data数据是否是一个完整的json
    int count = 0;      //括号的数量

    for(int i = 0; i < data.length(); i++)
    {
        if(count == 0)
        {
            //要求data以{开头
            if(data.at(i) != "{")
            {
                data = data.mid(1, data.length() - 1);
                i--;
                continue;
            }
        }
        if(data.at(i) == "{")
            count++;
        else if(data.at(i) == "}")
            count--;
        if(count == 0)
        {
            QString newData = data.left(i + 1);
            //newData 就是完整的一个Json数据
            emit receiveData(QJsonDocument::fromJson(newData.toLocal8Bit()).object());
            data = data.mid(i+1, data.length() - 1);
            i = -1;
        }
    }

}
